import React, { useState, useEffect } from 'react';
import { sensitiveWordsService, type SensitiveWord, type SensitiveWordsConfig } from '../services/sensitiveWordsService';
import './SensitiveWordsManager.css';

interface SensitiveWordsManagerProps {
    onClose: () => void;
}

const SensitiveWordsManager: React.FC<SensitiveWordsManagerProps> = ({ onClose }) => {
    const [words, setWords] = useState<SensitiveWord[]>([]);
    const [config, setConfig] = useState<SensitiveWordsConfig>(sensitiveWordsService.getConfig());
    const [newWord, setNewWord] = useState('');
    const [showAddForm, setShowAddForm] = useState(false);
    const [importText, setImportText] = useState('');
    const [showImportForm, setShowImportForm] = useState(false);

    // 加载敏感词列表
    useEffect(() => {
        loadWords();
    }, []);

    const loadWords = () => {
        setWords(sensitiveWordsService.getSensitiveWords());
    };

    const handleAddWord = () => {
        if (newWord.trim()) {
            sensitiveWordsService.addSensitiveWord(newWord.trim());
            setNewWord('');
            setShowAddForm(false);
            loadWords();
        }
    };

    const handleRemoveWord = (id: string) => {
        if (window.confirm('确定要删除这个敏感词吗？')) {
            sensitiveWordsService.removeSensitiveWord(id);
            loadWords();
        }
    };

    const handleToggleWord = (id: string) => {
        const word = words.find(w => w.id === id);
        if (word) {
            sensitiveWordsService.updateSensitiveWord(id, { enabled: !word.enabled });
            loadWords();
        }
    };

    const handleConfigChange = (key: keyof SensitiveWordsConfig, value: boolean | string) => {
        const newConfig = { ...config, [key]: value };
        setConfig(newConfig);
        sensitiveWordsService.saveConfig(newConfig);
    };

    const handleImport = () => {
        if (importText.trim()) {
            const wordList = importText.split('\n').map(w => w.trim()).filter(w => w);
            sensitiveWordsService.importWords(wordList);
            setImportText('');
            setShowImportForm(false);
            loadWords();
        }
    };

    const handleClearAll = () => {
        if (window.confirm('确定要清空所有敏感词吗？此操作不可恢复！')) {
            sensitiveWordsService.clearAllWords();
            loadWords();
        }
    };

    const handleExport = () => {
        const exportData = sensitiveWordsService.exportWords();
        const blob = new Blob([exportData], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'sensitive_words.txt';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    };

    return (
        <div className="sensitive-words-overlay">
            <div className="sensitive-words-panel">
                <div className="sensitive-words-header">
                    <h3>敏感词管理</h3>
                    <button className="sensitive-words-close" onClick={onClose}>
                        ✕
                    </button>
                </div>

                <div className="sensitive-words-content">
                    {/* 配置区域 */}
                    <div className="sensitive-words-config">
                        <h4>过滤设置</h4>
                        <div className="config-item">
                            <label>
                                <input
                                    type="checkbox"
                                    checked={config.enabled}
                                    onChange={(e) => handleConfigChange('enabled', e.target.checked)}
                                />
                                启用敏感词过滤
                            </label>
                        </div>
                        <div className="config-item">
                            <label>
                                <input
                                    type="checkbox"
                                    checked={config.replaceMode}
                                    onChange={(e) => handleConfigChange('replaceMode', e.target.checked)}
                                    disabled={!config.enabled}
                                />
                                替换模式（否则完全屏蔽）
                            </label>
                        </div>
                        <div className="config-item">
                            <label>
                                替换字符：
                                <input
                                    type="text"
                                    value={config.replaceChar}
                                    onChange={(e) => handleConfigChange('replaceChar', e.target.value)}
                                    disabled={!config.enabled || !config.replaceMode}
                                    maxLength={1}
                                    className="replace-char-input"
                                />
                            </label>
                        </div>
                        <div className="config-item">
                            <label>
                                <input
                                    type="checkbox"
                                    checked={config.caseSensitive}
                                    onChange={(e) => handleConfigChange('caseSensitive', e.target.checked)}
                                    disabled={!config.enabled}
                                />
                                区分大小写
                            </label>
                        </div>
                    </div>

                    {/* 敏感词列表 */}
                    <div className="sensitive-words-list">
                        <div className="list-header">
                            <h4>敏感词列表 ({words.length})</h4>
                            <div className="list-actions">
                                <button
                                    className="action-btn add-btn"
                                    onClick={() => setShowAddForm(true)}
                                >
                                    + 添加
                                </button>
                                <button
                                    className="action-btn import-btn"
                                    onClick={() => setShowImportForm(true)}
                                >
                                    导入
                                </button>
                                <button
                                    className="action-btn export-btn"
                                    onClick={handleExport}
                                >
                                    导出
                                </button>
                                <button
                                    className="action-btn clear-btn"
                                    onClick={handleClearAll}
                                >
                                    清空
                                </button>
                            </div>
                        </div>

                        <div className="words-list">
                            {words.length === 0 ? (
                                <div className="empty-state">
                                    <p>暂无敏感词</p>
                                    <button onClick={() => setShowAddForm(true)}>
                                        添加第一个敏感词
                                    </button>
                                </div>
                            ) : (
                                words.map(word => (
                                    <div key={word.id} className={`word-item ${!word.enabled ? 'disabled' : ''}`}>
                                        <div className="word-content">
                                            <span className="word-text">{word.word}</span>
                                            <span className="word-status">
                                                {word.enabled ? '启用' : '禁用'}
                                            </span>
                                        </div>
                                        <div className="word-actions">
                                            <button
                                                className="toggle-btn"
                                                onClick={() => handleToggleWord(word.id)}
                                            >
                                                {word.enabled ? '禁用' : '启用'}
                                            </button>
                                            <button
                                                className="delete-btn"
                                                onClick={() => handleRemoveWord(word.id)}
                                            >
                                                删除
                                            </button>
                                        </div>
                                    </div>
                                ))
                            )}
                        </div>
                    </div>

                    {/* 添加表单 */}
                    {showAddForm && (
                        <div className="add-form">
                            <h4>添加敏感词</h4>
                            <div className="form-group">
                                <input
                                    type="text"
                                    value={newWord}
                                    onChange={(e) => setNewWord(e.target.value)}
                                    placeholder="输入敏感词"
                                    className="word-input"
                                    onKeyPress={(e) => e.key === 'Enter' && handleAddWord()}
                                />
                                <div className="form-actions">
                                    <button onClick={handleAddWord} className="confirm-btn">
                                        添加
                                    </button>
                                    <button onClick={() => setShowAddForm(false)} className="cancel-btn">
                                        取消
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* 导入表单 */}
                    {showImportForm && (
                        <div className="import-form">
                            <h4>批量导入敏感词</h4>
                            <div className="form-group">
                                <textarea
                                    value={importText}
                                    onChange={(e) => setImportText(e.target.value)}
                                    placeholder="每行一个敏感词"
                                    className="import-textarea"
                                    rows={6}
                                />
                                <div className="form-actions">
                                    <button onClick={handleImport} className="confirm-btn">
                                        导入
                                    </button>
                                    <button onClick={() => setShowImportForm(false)} className="cancel-btn">
                                        取消
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

export default SensitiveWordsManager;
